package edu.bw.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.SQLException;

@Component
public class TransactionManager {

    @Autowired
    ConnectionFactory connectionFactory;

    @Autowired
    ThreadLocal<Connection> threadLocal;

    /**
     * 开启事务
     */
    public void beginTransaction(){
        try {
            connectionFactory.currentThreadConn().setAutoCommit(false);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 提交事务
     */
    public void commit(){
        try {
            connectionFactory.currentThreadConn().commit();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void rollback(){
        try {
            connectionFactory.currentThreadConn().rollback();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public void release(){
        try {
            connectionFactory.currentThreadConn().close();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        threadLocal.remove();//将数据库连接与当前线程解绑，解绑后该连接可以与其它线程绑定
    }


}
